package com.whz.governance.sensitive.engine;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Data;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author whz
 */
@Data
public class SkTrieNode {

    private final char key;

    private final boolean isEnd;

    private final Map<Character, SkTrieNode> children;

    public SkTrieNode(char key, boolean isEnd) {
        this.key = key;
        this.isEnd = isEnd;
        // 估计一个子节点个数
        children = new ConcurrentHashMap<>(1);
    }

    public SkTrieNode addChildAndReturnSkNode(char key, boolean isEnd) {
        if (children.containsKey(key)) {
            // 返回已经存在的树的根
            return children.get(key);
        }

        SkTrieNode value = new SkTrieNode(key, isEnd);
        children.putIfAbsent(key, value);
        // 返回子树的根
        return value;
    }

    /**
     * 从树根到当前节点敏感词是否完整了
     *
     * @return true 从树根到当前节点就是完整的敏感词
     */
    public boolean isComplete() {
        return isEnd || CollectionUtil.isEmpty(children);
    }

    /**
     * 按照关键词key获取当前节点下子节点
     *
     * @param key 关键词
     * @return 子节点树的根
     */
    public SkTrieNode getChild(Character key) {
        return children.get(key);
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof SkTrieNode)) {
            return false;
        }

        final SkTrieNode skNode = (SkTrieNode) o;

        return key == skNode.key;
    }

    @Override
    public int hashCode() {
        return key;
    }

}